/**
 * 
 */
package org.gov.vis.data.gui.listener;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ResourceBundle;

import javax.swing.JOptionPane;

import org.gov.vis.common.exceptions.InvalidInputException;
import org.gov.vis.data.controller.ProcurementLnCtlr;
import org.gov.vis.data.controller.ProcurementLnCtlrImpl;
import org.gov.vis.data.dto.ProcurementLNDto;
import org.gov.vis.data.gui.EditProcurementLNDialog;
import org.gov.vis.data.gui.ViewProcurementLNDialog;
import org.gov.vis.gui.util.ErrorsDisplayJPanel;
import org.gov.vis.main.Main;
import org.gov.vis.master.gui.listener.BaseListener;
import org.gov.vis.util.GuiConstants;
import org.gov.vis.util.Util;
import org.gov.vis.util.ValidatorUtils;

/**
 * @author user
 *
 */
public class EditProcurementLNListener implements ActionListener,BaseListener,FocusListener{

	final private ResourceBundle rb = Util.getResources();

	private ProcurementLnCtlr procurementLNCtlr = new ProcurementLnCtlrImpl();

	private EditProcurementLNDialog editProcurementLNDialog;

	private ErrorsDisplayJPanel errorMsgPanel;

	private ProcurementLNDto procurementLnDto;

	public EditProcurementLNListener(EditProcurementLNDialog editProcurementLNDialog) {
		// TODO Auto-generated constructor stub
		this.editProcurementLNDialog = editProcurementLNDialog;
	}

	@Override
	public void clear() {
		// TODO Auto-generated method stub

	}

	@Override
	public void setGuiDetailsToDto(Object _guiObject) {
		final EditProcurementLNDialog _editProcurementLNDialog = (EditProcurementLNDialog)_guiObject;
		procurementLnDto = new ProcurementLNDto();
		procurementLnDto.setCode(_editProcurementLNDialog.getTxtFldCode().getText());
		procurementLnDto.setCnvrtLtrs(_editProcurementLNDialog.getTxtFldLNConvertedLtrs().getText());
		if(_editProcurementLNDialog.getDtChoDateOfReceipt().getDate() != null){
			procurementLnDto.setDoRpt(_editProcurementLNDialog.getDtChoDateOfReceipt().getDate());
		}
		procurementLnDto.setFrmStation(_editProcurementLNDialog.getTxtFldLNFromStation().getText());
		procurementLnDto.setKgs(_editProcurementLNDialog.getTxtFldLNKgs().getText());
		procurementLnDto.setVehicleNo(_editProcurementLNDialog.getTxtFldLNVehicalNo().getText());
		procurementLnDto.setEvoprLoss(_editProcurementLNDialog.getTxtFldLNEvoporationLoss().getText());
		procurementLnDto.setPrLnId((Long)_editProcurementLNDialog.getHidnObject());


	}

	@Override
	public void setDtoDetailsToGui(Object _dtoObject) {
		// TODO Auto-generated method stub

	}

	@Override
	public void clearGUILabelColors(Color _labelColor) {
		// TODO Auto-generated method stub

	}

	@Override
	public void actionPerformed(ActionEvent actionEvent) {
		// TODO Auto-generated method stub

		errorMsgPanel = new ErrorsDisplayJPanel(editProcurementLNDialog.getjPanel1());
		errorMsgPanel.clearMsgPanel();


		if(actionEvent.getActionCommand().equals(rb.getString("dialog_button_update"))){

			//Method called to either Add or Edit the GopalaMithra details
			addOrEditProcurementLN();
		}

		if(actionEvent.getActionCommand().equals(rb.getString("dialog_button_delete"))){
			
			int response = JOptionPane.showConfirmDialog(null, GuiConstants.DELETE_CONFIRM_MSG, "Confirm",
			        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
			    
		    if (response == JOptionPane.YES_OPTION) {
		      // User clicked YES.
		    	deleteProcurementLN(actionEvent);
		    	String searchText = editProcurementLNDialog.getSearchText();

				// It is basically doing back button functionality. Please, understand the logic and write the comments.
				//Replace double quotes with appropriate Dialog title.
				ViewProcurementLNDialog viewProcLnDialog = new ViewProcurementLNDialog(Main.getMainFrame(), "View Procurement LN", false);
				for(ActionListener actionListener: viewProcLnDialog.getSearchBtn().getActionListeners()) { 
					ViewProcurementLNListener viewProcLnList = (ViewProcurementLNListener)actionListener;
					viewProcLnDialog.getCodeTxtBx().setText(searchText);

					viewProcLnList.actionPerformed(new ActionEvent(viewProcLnDialog.getSearchBtn(), 1, rb.getString("dialog_button_serach")));
				}

		    	
		    } else if (response == JOptionPane.NO_OPTION || response == JOptionPane.CLOSED_OPTION) {
		      return;
		    }

		}
	}

	private void addOrEditProcurementLN() {

		//Method called to set the Field's Labels to default Black color
		clearGUILabelColors(blackColor);

		//Method to set the Screen's data to  the DTO Object
		setGuiDetailsToDto(editProcurementLNDialog);

		try{
			//Method called to Add or Edit the GopalaMithra
			procurementLNCtlr.addOrEditPrLN(procurementLnDto);

			JOptionPane.showMessageDialog(editProcurementLNDialog, rb.getString(GuiConstants.DATA_EDIT_PROCUREMENTLN_SUCCESS));
			editProcurementLNDialog.dispose();
			
			String searchText = editProcurementLNDialog.getSearchText();

			// It is basically doing back button functionality. Please, understand the logic and write the comments.
			//Replace double quotes with appropriate Dialog title.
			ViewProcurementLNDialog viewProcLnDialog = new ViewProcurementLNDialog(Main.getMainFrame(), "View Procurement LN", false);
			for(ActionListener actionListener: viewProcLnDialog.getSearchBtn().getActionListeners()) { 
				ViewProcurementLNListener viewProcLnList = (ViewProcurementLNListener)actionListener;
				viewProcLnDialog.getCodeTxtBx().setText(searchText);

				viewProcLnList.actionPerformed(new ActionEvent(viewProcLnDialog.getSearchBtn(), 1, rb.getString("dialog_button_serach")));
			}

		}catch(Exception e){
			List<String> errorMsgLst = new ArrayList<String>();
			if(e instanceof InvalidInputException){
				final HashMap<String,String> _exceptions = ProcurementLnCtlr.errorMsgs;
				if (_exceptions != null && !_exceptions.isEmpty()) {
					String errMsg = null;

					if(_exceptions.containsKey(rb.getString("dialog_label_prmt_ln_code").toUpperCase())){
						editProcurementLNDialog.getLblCode().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_prmt_ln_code").toUpperCase());
						errorMsgLst.add(errMsg);
					}
					if(_exceptions.containsKey(rb.getString("dialog_label_prmt_ln_dtofrcpt").toUpperCase())){
						editProcurementLNDialog.getLblDateOfReceipt().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_prmt_ln_dtofrcpt").toUpperCase());
						errorMsgLst.add(errMsg);
					}
					if(_exceptions.containsKey(rb.getString("dialog_label_prmt_ln_frmstation").toUpperCase())){
						editProcurementLNDialog.getLblFromStation().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_prmt_ln_frmstation").toUpperCase());
						errorMsgLst.add(errMsg);
					}

					if(_exceptions.containsKey(rb.getString("dialog_label_prmt_ln_vehicleno").toUpperCase())){
						editProcurementLNDialog.getLblVehicalNo().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_prmt_ln_vehicleno").toUpperCase());
						errorMsgLst.add(errMsg);
					}
					if(_exceptions.containsKey(rb.getString("dialog_label_prmt_ln_kgs").toUpperCase())){
						editProcurementLNDialog.getLblKgs().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_prmt_ln_kgs").toUpperCase());
						errorMsgLst.add(errMsg);
					}

					errorMsgPanel.setErrorMessages(errorMsgLst);					
				} else {
					//log.debug(e.getMessage(), e);
				}
			}
			else{
				errorMsgLst.add(e.getMessage());
				errorMsgPanel.setErrorMessages(errorMsgLst);
			}
		}		


	}

	private void deleteProcurementLN(ActionEvent actionEvent) {

		Long distributionLNsId = (Long)editProcurementLNDialog.getHidnObject();
		try {
			procurementLNCtlr.deletePrLN(distributionLNsId);
			JOptionPane.showMessageDialog(editProcurementLNDialog, rb.getString(GuiConstants.DATA_DELETE_PROCUREMENTLN_EXCEPTION));
			editProcurementLNDialog.dispose();
		} catch (Exception e) {

			List<String> errorMsgLst = new ArrayList<String>();
			errorMsgLst.add(e.getMessage());
			errorMsgPanel.setErrorMessages(errorMsgLst);

		}
	}


	@Override
	public void focusGained(FocusEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void focusLost(FocusEvent arg0) {
		// TODO Auto-generated method stub
		errorMsgPanel = new ErrorsDisplayJPanel(editProcurementLNDialog.getjPanel1());
		errorMsgPanel.clearMsgPanel();
		clearGUILabelColors(blackColor);

		convertKgsToLitters();
	}	
	private void convertKgsToLitters() {

		HashMap<String, String> errorMsgs = new HashMap<String, String>();
		List<String> errorMsgLst = new ArrayList<String>();
		try{
			String _disLNKgsErr = ValidatorUtils.validateDecimal(rb.getString("dialog_label_dist_ln_kgs"),editProcurementLNDialog.getTxtFldLNKgs().getText() , ValidatorUtils.DECIMALS, 0, Double.MAX_VALUE, 0, 2, false, false);
			if(_disLNKgsErr != null)
				errorMsgs.put(rb.getString("dialog_label_dist_ln_kgs").toUpperCase(), _disLNKgsErr);
			if (errorMsgs != null && !errorMsgs.isEmpty())
				throw new InvalidInputException();
			double kgs = Double.parseDouble(editProcurementLNDialog.getTxtFldLNKgs().getText());
			double litters = kgs * 1.078;
			editProcurementLNDialog.getTxtFldLNConvertedLtrs().setText(String.valueOf(litters));


		}catch(InvalidInputException iie){
			String errMsg = null;
			if(errorMsgs.containsKey(rb.getString("dialog_label_dist_ln_kgs").toUpperCase())){
				editProcurementLNDialog.getLblKgs().setForeground(redColor);
				errMsg = errorMsgs.remove(rb.getString("dialog_label_dist_ln_kgs").toUpperCase());
				errorMsgLst.add(errMsg);
			}

			errorMsgPanel.setErrorMessages(errorMsgLst);

		}
	}




}
